package mark.tom.sail;

import androidx.annotation.NonNull;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

class DefaultFileGenerator implements FileGenerator {

    private final static String RECORD_FILE_SEPARATOR = "_";

    // 单文件中的数据最大条目数
    private final int limited;
    // 文件内容计数器
    private static final Map<String, Integer> fileContentCounter = new ConcurrentHashMap<>();

    DefaultFileGenerator(int limited) {
        this.limited = limited;
    }

    @Override
    public String generate(@NonNull String tag, @NonNull String idKey) {
        if (checkFileNameValidity(tag) || checkFileNameValidity(idKey)) {
            throw new IllegalArgumentException();
        }
        String filePrefix = tag + RECORD_FILE_SEPARATOR + idKey;
        String suffix = "0";
        if (fileContentCounter.containsKey(filePrefix)) {
            Integer count = fileContentCounter.get(filePrefix);
            if (count != null && count > 0) {
                suffix = String.valueOf(count / limited);
            }
            fileContentCounter.put(filePrefix, count == null ? 1 : count + 1);
        } else {
            fileContentCounter.put(filePrefix, 1);
        }
        return filePrefix + RECORD_FILE_SEPARATOR + suffix;
    }

    @Override
    public String tag(@NonNull String fileName) {
        if (!checkFileNameValidity(fileName)) {
            throw new IllegalArgumentException();
        }
        return fileName.substring(0, fileName.indexOf(RECORD_FILE_SEPARATOR));
    }

    @Override
    public String key(@NonNull String fileName) {
        if (!checkFileNameValidity(fileName)) {
            throw new IllegalArgumentException();
        }
        return fileName.substring(fileName.indexOf(RECORD_FILE_SEPARATOR) + 1, fileName.lastIndexOf(RECORD_FILE_SEPARATOR));
    }

    @Override
    public boolean compare(@NonNull String obj, @NonNull String target) {
        boolean result = false;
        try {
            result = (Long.parseLong(obj) - Long.parseLong(target) > 0);
        } catch (Exception ex) {
            // ignore
        }
        return result;
    }

    private boolean checkFileNameValidity(@NonNull String name) {
        return name.contains(RECORD_FILE_SEPARATOR);
    }
}
